package com.xiaohe66.web.infrastructure.sec.filter;

import com.xiaohe66.common.web.util.SecConst;
import com.xiaohe66.web.domain.sys.sec.entity.CurrentAccount;
import com.xiaohe66.web.domain.sys.sec.service.SecurityService;
import com.xiaohe66.web.infrastructure.sec.config.TokenLoginConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author He
 * @since 2024.01.17 15:02
 */
@RequiredArgsConstructor
@Component
@Slf4j
public class TokenLoginFilter implements Filter {

    private final TokenLoginConfig config;
    private final SecurityService securityService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init TokenLoginFilter, excludeUrl : {}", config.getExcludeUrl());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (!securityService.isLogin()) {

            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String uri = request.getRequestURI();

            if (!config.getExcludeUrl().contains(uri)) {

                log.info("token login");

                String authorization = request.getHeader("Authorization");
                if (authorization != null && authorization.startsWith("Bearer ")) {

                    String token = authorization.substring("Bearer ".length());

                    CurrentAccount currentAccount = securityService.verifyTokenAndGet(token);

                    try {
                        securityService.login(currentAccount);
                        securityService.setCurrentAccount(currentAccount);

                        log.info("token login success, account : {}", currentAccount.getName());

                    } catch (Exception e) {
                        log.error("token login error", e);
                    }
                }
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
